<?php
namespace app\index\controller;
use think\Controller;
use Firebase\JWT\JWT;
use think\Cache;

class Partlogin extends Controller
{
    public $app_id        = "101846938";
    public $app_secret    = "7e7afdcce924291a7890b1d37b858693";
    public $call_back_url = 'http://www.taoerhuo.top/bishe/public/index.php/index/Partlogin/callback';

    public $url = 'http://taoerhuo.top/html/login/bindEmail.html';

    public function __construct()
    {
        header("Access-Control-Allow-Origin: *");//允许跨域
        header('Content-type: application/json');
        header("Access-Control-Allow-Methods:POST");
        header("access-control-allow-headers: Origin, X-Requested-With, Content-Type, Accept,WG-App-Version, WG-Device-Id, WG-Network-Type, WG-Vendor, WG-OS-Type, WG-OS-Version, WG-Device-Model, WG-CPU, WG-Sid, WG-App-Id, WG-Token,authorization");
    }

    //打开qq登录页面
    public function openQQ()
    {
        $app_id = $this->app_id;
        //回调地址
        $redirect_uri = urlencode($this->call_back_url);
        $url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=".$app_id."&redirect_uri=".$redirect_uri."&scope=get_user_info&state=text";
        //跳转到$url

        $this->redirect($url);
    }

    /**
     * 登录回调
     */
    public function callback()
    {
        $app_id = $this->app_id;
        //appkey
        $app_secret = $this->app_secret;
        //成功授权后的回调地址
        $my_url = urlencode($this->call_back_url);
        //获取code
        $code = $_GET['code'];
        //Step2：通过Authorization Code获取Access Token
        $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=".$app_id."&redirect_uri=".$my_url."&client_secret=".$app_secret."&code=".$code."";
        $response = file_get_contents($token_url);
        //Step3:在上一步获取的Access Token，得到对应用户身份的OpenID。
        $params = array();
        //parse_str() 函数把查询字符串（'a=x&b=y'）解析到变量中。
        parse_str($response,$params);

        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params['access_token']."";
        $str = file_get_contents($graph_url);
        // --->找到了字符串：callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} )
        // strpos() 函数查找字符串在另一字符串中第一次出现的位置，从0开始
        if(strpos($str,"callback")!==false)
        {
            $lpos = strpos($str,"(");
            // strrpos() 函数查找字符串在另一字符串中最后一次出现的位置。
            $rpos = strrpos($str,")");
            //substr(string,start,length) 截取字符串某一位置
            $str = substr($str,$lpos+1,$rpos-$lpos-1);
        }

        $user = json_decode($str);

        //判断这个openid是否在数据表中存在，存在则说明已绑定过返回绑定的信息即可，不存在则强制绑邮箱
        $check = db('user',[],false)->where('us_openid_qq',$user->openid)->find();

        if ($check) {
            $info['code']    = '200';
            $info['message'] = '登录成功';
            $info['uid']     = $check['us_id'];
            $info['account'] = $check['us_email'];
            $info['username']= $check['us_username'];
            $info['image']   = $check['us_image'];
            $info['jwt']     = self::createJwt($check['us_id']);  //生成jwt
        } else {
            $qq_user = "https://graph.qq.com/user/get_user_info?access_token=".$params['access_token']."&oauth_consumer_key=".$app_id."&openid=".$user->openid."";
            //加上true，得到数组，否则默认得到对象
            $res = json_decode(file_get_contents($qq_user),true);

            //需要强制绑定邮箱
            $info['code']       = '201';
            $info['message']    = '请先绑定邮箱';
            $info['nickname']   = $res['nickname']; //昵称
            $info['head_image'] = $res['figureurl_qq_1']; //头像
            $info['sex']        = $res['gender'] == '男' ? 1 : 2; //性别
            $info['openid_qq']  = $user->openid;


        }

        $param_str = base64_encode(createSignStr($info,false,true)); //参数加密

        $this->redirect($this->url.'?param='.$param_str);
    }

    /**
     * 中间层接口 供页面调用
     */
    public function baseDecode()
    {
        $param  = input('param');

        $decode = base64_decode($param); //参数解密

        $info   = convertUrlArray($decode); //url字符串转数组

        echo displayJson($info);die;
    }

    /**
     * 绑邮箱操作
     */
    public function bindEmail()
    {
        $email      = input('email');
        $openid_qq  = input('openid_qq');
        $head_image = input('head_image');
        $nickname   = input('nickname');
        $sex        = input('sex');
        $code       = input('code');

        if (!$email) {
            $info['code']       = '400';
            $info['message']    = '请输入要绑定的邮箱';
            echo displayJson($info);die;
        }

        if (!plum_is_email($email)) {
            $info['code']       = '400';
            $info['message']    = '邮箱格式错误';
            echo displayJson($info);die;
        }

        if (!$openid_qq) {
            $info['code']       = '400';
            $info['message']    = '数据错误';
            echo displayJson($info);die;
        }

        $checkCode = Cache::get($email);

        if (!$checkCode) {
            $info['code']    = 400;
            $info['message'] = '验证码失效，请重新获取';
            echo displayJson($info);die;
        }

        if (trim($code) !== $checkCode) {
            $info['code']    = '400';
            $info['message'] = '验证码错误';
            echo displayJson($info);die;
        }

        //判断邮箱
        $row = db('user',[],false)->where('us_email',$email)->find();

        if ($row) {
            if ($row['us_openid_qq'] && $row['us_openid_qq'] !== $openid_qq) {
                $info['code']       = '400';
                $info['message']    = '该邮箱已被绑定，请更换';
                echo displayJson($info);die;
            } else {
                //执行更新
                $set['us_openid_qq'] = $openid_qq;

                $res = db('user',[],false)->where('us_id',$row['us_id'])->update($set);

                if ($res) {
                    //删除Redis数据
                    Cache::rm($email);

                    $info['code']       = '200';
                    $info['message']    = '绑定成功';
                    $info['uid']        = $row['us_id'];
                    $info['account']    = $row['us_email'];
                    $info['username']   = $row['us_username'];
                    $info['image']      = $row['us_image'];
                    $info['jwt']        = self::createJwt($row['us_id']);  //生成jwt
                    echo displayJson($info);die;
                } else {
                    $info['code']       = '400';
                    $info['message']    = '绑定失败,请稍后重试';
                    echo displayJson($info);die;
                }
            }
        } else {
            //添加账号
            $add['us_openid_qq']  = $openid_qq;
            $add['us_image']      = $head_image;
            $add['us_email']      = $email;
            $add['us_password']   = md5(__DEFAULT_PWD__.'SecretIndex');
            $add['us_username']   = $nickname;
            $add['us_sex']        = $sex;
            $add['us_create_time']= time();

            $insert = db('user',[],false)->insertGetId($add);

            if ($insert) {
                //删除Redis数据
                Cache::rm($email);

                $newUser = db('user',[],false)->where('us_id',$insert)->find();

                $info['code']       = '200';
                $info['message']    = '绑定成功';
                $info['uid']        = $newUser['us_id'];
                $info['account']    = $newUser['us_email'];
                $info['username']   = $newUser['us_username'];
                $info['image']      = $newUser['us_image'];
                $info['jwt']        = self::createJwt($newUser['us_id']);  //生成jwt
                echo displayJson($info);die;
            } else {
                $info['code']       = '400';
                $info['message']    = '绑定失败,请稍后重试';
                echo displayJson($info);die;
            }
        }
    }

    /**
     * 绑邮箱发送验证码
     */
    public function bindEmailGetCode()
    {
        $email      = input('email');
        $openid_qq  = input('openid_qq');

        if (!$email) {
            $info['code']       = '400';
            $info['message']    = '请输入要绑定的邮箱';
            echo displayJson($info);die;
        }

        if (!plum_is_email($email)) {
            $info['code']       = '400';
            $info['message']    = '邮箱格式错误';
            echo displayJson($info);die;
        }

        if (!$openid_qq) {
            $info['code']       = '400';
            $info['message']    = '数据错误';
            echo displayJson($info);die;
        }

        //判断邮箱
        $row = db('user',[],false)->where('us_email',$email)->find();

        if ($row) {
            if ($row['us_openid_qq'] && $row['us_openid_qq'] !== $openid_qq) {
                $info['code']       = '400';
                $info['message']    = '该邮箱已被绑定，请更换';
                echo displayJson($info);die;
            } else {
                //发送邮件
                $goSend = true;
            }
        } else {
            $goSend = true;
        }

        if ($goSend) {
            $code      = make_Verification_Code(6);
            $send_data = array(
                'to_email'   =>$email,
                'content'    =>'【淘二货】欢迎使用校内二手物品交易平台，您正在进行绑定邮箱操作,此次的验证码为：<span style="font-size: 24px;font-weight: bold;"> '.$code.' </span>，请在10分钟内完成验证'
            );

            $send      = sendEmail($send_data);

            if (!$send) {
                $info['code']    = '400';
                $info['message'] = '邮件发送失败';
                echo displayJson($info);die;
            } else {
                $check_code = explode(' ',$send_data['content']);

                // 设置redis
                $options = ['type'  => 'Redis']; //指定类型
                Cache::init($options);//初始化
                Cache::set($email,$check_code['4'],600); //redis key有效期为10分钟

                $info['code']         = '200';
                $info['message']      = '邮件发送成功';
                echo displayJson($info);die;
            }
        }
    }


    /**
     * 生成jwt
     * @param $userId
     * @return string
     */
    public function createJwt($userId)
    {
        $key    = md5('taoerhuo'); //jwt的签发密钥，验证token的时候需要用到
        $time   = time(); //签发时间
        $expire = $time + 604800; //过期时间(7天)
        $token  = array(
            "us_id" => $userId,
            "iss" => "http://taoerhuo.top",//签发组织
            "aud" => "YeWenHao", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );

        $jwt = JWT::encode($token, $key);
        return $jwt;
    }
    

}